package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.entity.Sku;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

    private static final String UPDATE_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.deductStock";

    //根据SpuId查询SKU集合
    @Override
    public List<SkuDTO> querySkuBySpuId(Long spuId) {
        List<Sku> skuList = this.query().eq("spu_id", spuId).list();
        List<SkuDTO> skuDTOList = SkuDTO.convertEntityList(skuList);
        return skuDTOList;
    }

    /*//扣减库存  skuMap的  key：skuId，value：扣减数量
    @Override
    @Transactional
    public void deductStock(Map<Long, Integer> skuMap) {
        //1.遍历
        Set<Map.Entry<Long, Integer>> entrySet = skuMap.entrySet();
        for (Map.Entry<Long, Integer> entry : entrySet) {
            Map<String,Object> param = new HashMap<>();
            param.put("num",entry.getValue());
            param.put("id",entry.getKey());
            //调用mapper方法
            int count = this.baseMapper.deductStock(param);
            if (count==0){
                throw new LyException(400,"更新库存失败，可能时已经下架了！");
            }
        }
    }*/

    //继续优化  进行批处理 批量删除
    //扣减库存  skuMap的  key：skuId，value：扣减数量
    @Override
    @Transactional
    public void deductStock(Map<Long, Integer> skuMap) {
        try {
            executeBatch(sqlSession -> {
                // 遍历sku
                for (Map.Entry<Long, Integer> entry : skuMap.entrySet()) {
                    // 调用mapper中的方法
                    Map<String, Object> param = new HashMap<>();
                    param.put("id", entry.getKey());
                    param.put("num", entry.getValue());
                    // 编译Sql，第一个参数：可以是sql，也可以是statementId：mapper接口名.方法名
                    // 第二个参数是sql需要的参数
                    sqlSession.update(UPDATE_STOCK_STATEMENT, param);
                }
                //刷新和提交
                sqlSession.flushStatements();
            });
        } catch (Exception e) {
            throw new LyException(400,"库存不足！");
        }
    }
}
